import type { PayloadAction } from "@reduxjs/toolkit"
import { createSlice } from "@reduxjs/toolkit"
import type { User } from "@/app/user/interfaces"

interface IUserState {
  user: User | null
}

const initialState: IUserState = {
  user: null,
}

export const userSlice = createSlice({
  initialState,
  name: "userSlice",
  reducers: {
    logout: () => {
      localStorage.removeItem("token")
      return initialState
    },
    setUser: (state, action: PayloadAction<User>) => {
      state.user = action.payload
    },
  },
  selectors: { selectUser: state => state.user },
})

export default userSlice.reducer

export const { logout, setUser } = userSlice.actions
export const { selectUser } = userSlice.selectors
